<script lang="ts">
export default {
  name: "loginPage"
}
</script>
<template>
  <div v-if="isShowCode == true">{{code}} | {{ returnData }}</div>
  <div class="loginSuccess" v-if="isSuccess === 1">
    <el-icon size="44" color="#67C23A"><Select/></el-icon>
    <div>授权成功</div>
  </div>
  <div class="loginSuccess" v-else-if="isSuccess === 2" @click="isShowCode = true">
    <h3>小虎海拍</h3>
    <img class="down-img" src="@/assets/images/down.png" alt="↓">
    <span>请点击下方【使用完整服务】</span>
  </div>
  <div class="loginSuccess" v-else-if="isSuccess === 3" @click="isShowCode = true">
    <el-icon size="44" color="#F56C6C"><WarningFilled /></el-icon>
    <span>授权失败，请重新扫码或联系客服</span>
  </div>
  <div class="loginSuccess" v-else>
    <span>正在授权...</span>
  </div>
  <!--<button @click="handleWechatLogin">授权登录</button>-->
</template>
<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {useRoute} from 'vue-router'
import API from "./../server"
import Https from "@/server";
import {ElMessage} from "element-plus";

const route = useRoute();
const code = ref("") // 微信返回的授权码
const state = ref("") // 验证 state 防止 CSRF
const isSuccess = ref(0);
const countNum = ref(0);
const returnData = ref("");
const isShowCode = ref(false);

const userLogin = () => {
  let data = {
    code: code.value,
    random_code: state.value,
  }
  API.login(data).then((res: any) => {
    returnData.value = res;
    if (res.code == 0) {
      isSuccess.value = 1;
    } else {
      isSuccess.value = 2;
      userStatus();
    }
  })

}

const userStatus = () => {
  countNum.value += 1;
  if (countNum.value < 100) {
    Https.getUserLoginStatus(state.value).then((res: any) => {
      // console.log(res);
      if (res.data == null) {
        let ct = setTimeout(() => {
          userStatus();
          clearTimeout(ct);
        }, 3000)
      } else {
        if(res.data.username == "微信用户"){
          let ct = setTimeout(() => {
            userStatus();
            clearTimeout(ct);
          }, 3000)
        }
      }
    })
  } else {
    ElMessage.warning("请点击【使用完整服务】完成授权")
  }

}


onMounted(async () => {
  code.value = route.query.code as string;
  state.value = route.query.state as string;
  userLogin();
})
</script>

<style scoped lang="scss">
.loginSuccess {
  display: flex;
  height: 100vh;
  width: 100%;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  h3{
    font-size: 2rem;
    margin: 0;
    color: var(--el-color-primary);
  }

  .down-img{
    position: fixed;
    right: 30px;
    bottom: 100px;
    width: 40px;
  }

  div{
    color: var(--main-color);
    font-size: 22px;
    padding-top: 20px;
  }

  span{
    color: var(--main-color);
    font-size: 16px;
    padding-top: 20px;
  }
}
</style>